using System;
using Microsoft.SPOT;

namespace GizmoProject
{
    public class Robot
    {
        public double speed = 1; // stypka
        private Random random = new Random();

        Board board;
        public bool noisy;
        int stepCount;

        public double Heading;

        public double x;
        public double y;

        public Robot( Board board )
            : this( 0, 0, 0, false, board )
        {
        }

        public Robot( double x, double y, double heading, bool noisy, Board board )
        {
            this.x = x;
            this.y = y;
            this.Heading = heading;
            this.noisy = noisy;
            this.board = board;
            stepCount = 0;
        }

        public void ReadSensor()
        {
            //TODO
        }

        public bool IsNextToObstacle
        {
            get
            {
                int rad = ( int )( this.Heading * System.Math.PI / 180 );
                double dx = Microsoft.SPOT.Math.Sin( rad ) * speed;
                double dy = Microsoft.SPOT.Math.Cos( rad ) * speed;

                if ( board.IsEmpty( ( int )( x + dx ), ( int )( y + dy ) ) )
                {
                    return true;
                }
                return false;
            }

        }

        public bool Move()
        {
            bool hasMoved = false;

            while ( hasMoved == false )
            {
                hasMoved = this.AdvanceBy( speed, noisy );
                if ( hasMoved == false )
                    this.RandomHeading();
            }

            return true; // the robot has moved
        }

        bool AdvanceBy( double speed, bool noisy )
        {
            if ( noisy )
            {// not noisy
            }

            int rad = ( int )( this.Heading * System.Math.PI / 180 );
            double dx = Microsoft.SPOT.Math.Sin( rad ) * speed;
            double dy = Microsoft.SPOT.Math.Cos( rad ) * speed;

            if ( board.IsEmpty( ( int )( this.x + dx ), ( int )( this.y + dy ) ) )
            {
                this.x += dx;
                this.y += dy;
                
                return true;
            }

            return false;
        }

        void RandomHeading()
        {
            int x = this.random.Next( 50 );
            this.Heading = x % 2 == 0 ? this.Heading + 90 : this.Heading - 90;
        }
    }
}
